<template>
  <div>
    <el-card>
      
      <el-button
        type="primary"
        icon="Plus"
        @click="addTrademark"
        v-has="`btn.Trademark.add`"
        >添加品牌</el-button
      >
      <el-table border style="width: 100%; margin: 15px 0" :data="tableData">
        <el-table-column prop="id" label="序号" width="120" align="center" />
        <el-table-column prop="tmName" label="品牌名称" align="center" />
        <el-table-column label="品牌LOGO" align="center">
          <template #="{ row, $index }">
            <img
              :src="row.logoUrl"
              style="width: 90px; height: 90px"
              @error="handleImageError"
              v-if="row.logoUrl"
            />
            <img :src="imageSrc" style="width: 90px; height: 90px" v-else />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作" align="center">
          <template #="{ row, $index }">
            <el-button
              icon="Edit"
              size="small"
              type="warning"
              @click="updateTrademark(row)"
            ></el-button>
            <el-button
              icon="Delete"
              size="small"
              type="danger"
              @click="deleteTrademark(row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7]"
        :background="true"
        layout=" prev, pager, next, jumper,->, sizes,total"
        :total="totalPage"
        @current-change="getProInfo"
        @size-change="updateProInfo"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      :title="trademarkInfo.id ? '修改品牌' : '添加品牌'"
      width="500"
    >
      <el-form
        :inline="true"
        :model="trademarkInfo"
        class="demo-form-inline"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="80px" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            clearable
            v-model="trademarkInfo.tmName"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="80px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            {{ uploadImage }}
            <template #file="{ file }">
              <img class="el-upload-list__item-thumbnail" :src="file.url" />
            </template>
            <img
              v-if="trademarkInfo.logoUrl"
              :src="trademarkInfo.logoUrl"
              @error="handleImageError"
              class="avatar"
              style="width: 178px; height: 178px"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelUpload">取消</el-button>
          <el-button type="primary" @click="confirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
import {
  reqDeleteTrademark,
  reqProInfo,
  reqSaveOrUpdateTrademark,
} from "../../../api/product/trademark";
import imageSrc from "@/assets/login_img2.png"; // 替换为你的图片路径
import { ElMessage } from "element-plus";
import Confirm from "../../../utils/confirm";
import type { UploadProps } from "element-plus";
import {
  proInfoResponseForm,
  recordForm,
  trademarkForm,
} from "../../../api/product/trademark/type";
reactive;
let currentPage = ref<number>(1);
let pageSize = ref<number>(4);
let totalPage = ref<number>(400);
let tableData = ref<recordForm[]>([]);
let dialogVisible = ref<boolean>(false);
let uploadImage = ref();
const formRef = ref();
let trademarkInfo = reactive<trademarkForm>({ tmName: "", logoUrl: "" });
interface RuleForm {
  tmName: string;
  logoUrl: string;
}
// 验证logo名称
const validateTmName = (rules: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback();
  } else {
    callback(new Error("名称长度应不小于2"));
  }
};
// 验证logo图片
const validateLogoUrl = (rules: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请上传正确格式的图片"));
  } else {
    callback();
  }
};
const rules = {
  tmName: [{ required: true, trigger: "blur", validator: validateTmName }],
  logoUrl: [{ required: true, trigger: "blur", validator: validateLogoUrl }],
};
const getProInfo = async () => {
  let result: proInfoResponseForm = await reqProInfo(
    currentPage.value,
    pageSize.value
  );
  totalPage.value = result.data.total;
  tableData.value = result.data.records;
};

onMounted(() => {
  getProInfo();
});

const handleImageError = (event: Event) => {
  // console.log("error handle");
  const imgElement = event.target as HTMLImageElement;
  imgElement.src = imageSrc;
};
const updateProInfo = () => {
  currentPage.value = 1;
  getProInfo();
};
// 添加品牌
const addTrademark = () => {
  Object.assign(trademarkInfo, { tmName: "", logoUrl: "", id: "" });
  dialogVisible.value = true;
  nextTick(() => {
    formRef.value.resetFields();
  });
};
// 更新品牌
const updateTrademark = (row: any) => {
  dialogVisible.value = true;
  trademarkInfo.id = row.id;
  trademarkInfo.tmName = row.tmName;
  trademarkInfo.logoUrl = row.logoUrl;
  nextTick(() => {
    formRef.value.resetFields();
  });
};

const cancelUpload = () => {
  dialogVisible.value = false;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile: any) => {
  console.log(rawFile.type);
  if (
    (rawFile.type === "image/jpeg" ||
      "image/png" ||
      "image/gif" ||
      "image/jpg") &&
    rawFile.size / 1024 / 1024 < 4
  ) {
    return true;
  } else {
    ElMessage.error("上传的格式不符合要求!");
    return false;
  }
};
const handleAvatarSuccess: UploadProps["onSuccess"] = (response: any) => {
  trademarkInfo.logoUrl = response.data;
};

// 上传、更新品牌
const confirm = () => {
  formRef.value.validate(async (valid: any) => {
    if (!valid) return;
    let result = await reqSaveOrUpdateTrademark(trademarkInfo);
    if (result.code === 200) {
      getProInfo();
      ElMessage.success("上传成功");
      dialogVisible.value = false;
    } else {
      console.log(result);
      ElMessage.error("上传失败");
    }
  });
};
// 删除品牌
const deleteTrademark = (id: number) => {
  Confirm("你确定要删除该品牌吗?", async () => {
    let result = await reqDeleteTrademark(id);
    if (result.code === 200) {
      ElMessage.success("删除成功");
      getProInfo();
    } else {
      ElMessage.error("删除失败");
    }
  });
};
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
